package com.molichuxing.gateway.bff.risk.services.impl;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.commons.lang3.StringUtils;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import com.alibaba.fastjson.JSONObject;
import com.molichuxing.framework.exception.BizException;
import com.molichuxing.framework.result.ResponseResult;
import com.molichuxing.framework.utils.DateUtil;
import com.molichuxing.framework.utils.DingTalkUtil;
import com.molichuxing.framework.utils.EmailUtil;
import com.molichuxing.framework.utils.PoiExcelUtils;
import com.molichuxing.gateway.bff.risk.entity.request.create.DrivingLicenseOcrCreateVo;
import com.molichuxing.gateway.bff.risk.entity.request.create.IdentityCreateVo;
import com.molichuxing.gateway.bff.risk.entity.response.DrivingLicenseOcrVo;
import com.molichuxing.gateway.bff.risk.services.RiskBffService;
import com.molichuxing.gateway.bff.user.convertor.Convert;
import com.molichuxing.gateway.bff.user.entity.response.UserVo;
import com.molichuxing.gateway.utils.RequestAttrUtil;
import com.molichuxing.gateway.utils.redis.TokenUtil;
import com.molichuxing.services.business.dto.request.create.DrivingLicenseCreateDto;
import com.molichuxing.services.business.dto.request.create.IdentityCreateDto;
import com.molichuxing.services.business.dto.request.create.MobileCreateDto;
import com.molichuxing.services.business.dto.response.CreditDto;
import com.molichuxing.services.business.dto.response.DriverLicenseDto;
import com.molichuxing.services.business.dto.response.DriverLicenseOcrDto;
import com.molichuxing.services.business.dto.response.UserBizDto;
import com.molichuxing.services.business.service.DrivingLicenseBizService;
import com.molichuxing.services.business.service.IdentityBizService;
import com.molichuxing.services.business.service.MobileBizService;
import com.molichuxing.services.business.service.SmsBizService;
import com.molichuxing.services.business.service.UserBizService;
import com.molichuxing.services.infrastructure.dto.request.create.CreditRecognitionCreateDto;
import com.molichuxing.services.infrastructure.dto.request.create.DrivingLicenseRecognitionCreateDto;
import com.molichuxing.services.infrastructure.dto.request.create.FaceRecognitionCreateDto;
import com.molichuxing.services.infrastructure.dto.request.modify.DrivingLicenseModifyDto;
import com.molichuxing.services.infrastructure.dto.response.BlacklistDto;
import com.molichuxing.services.infrastructure.dto.response.DrivingLicenseDto;
import com.molichuxing.services.infrastructure.dto.response.MessageTemplateDto;
import com.molichuxing.services.infrastructure.dto.response.RiskEmailDto;
import com.molichuxing.services.infrastructure.service.BlacklistService;
import com.molichuxing.services.infrastructure.service.CreditRecognitionService;
import com.molichuxing.services.infrastructure.service.DrivingLicenseRecognitionService;
import com.molichuxing.services.infrastructure.service.DrivingLicenseService;
import com.molichuxing.services.infrastructure.service.FaceRecognitionService;
import com.molichuxing.services.infrastructure.service.FicoCreditInvestigationService;
import com.molichuxing.services.infrastructure.service.MessageTemplateService;
import com.molichuxing.services.infrastructure.service.RiskEmailService;
import com.molichuxing.services.infrastructure.service.UserService;
import com.molichuxing.services.property.CreditVerifySourceEnum;
import com.molichuxing.services.property.DrivingLicenseDataSourceEnum;
import com.molichuxing.services.property.DrivingLicenseStatusEnum;
import com.molichuxing.services.property.RiskEmailReceiveTypeEnum;
import com.molichuxing.services.property.RiskEmailTypeEnum;
import com.molichuxing.services.property.SmsTemplateEnum;
import com.molichuxing.services.property.VerifyResultEnum;

/**
 * 
 * @author 李义广
 * 风控服务实现类
 * 2019-09-24
 *
 */
@Service("riskBffService")
public class RiskBffServiceImpl implements RiskBffService{
	
	private static final Logger logger = LoggerFactory.getLogger(RiskBffServiceImpl.class);
	
	
	private static final String drivingLicenceAuditDing ="dingTalk_drivingLicence_audit";
	private static final String drivingLicenceAuditEmail ="email_drivingLicence_audit";

	@Value("${driving_licence_audit_url}")
	private String drivingLicenceAuditUrl;

	@Value("${verify.days}")
	private Integer verifyDays;
	
	@Value("${email.account}")
	private String emailAccount;
	
	@Value("${email.password}")
	private String emailPassword;
	
	@Value("${fico.is.true}")
	private Boolean ficoIsTrue;
	
	@Resource
	private UserService userService;
	
	@Resource
	private TokenUtil tokenUtil;
	
	@Resource
	private DrivingLicenseService drivingLicenseService;
	
	@Resource
	private IdentityBizService identityBizService;
	
	@Resource
	private MobileBizService mobileBizService;
	
	@Resource
	private FaceRecognitionService faceRecognitionService;
	
	@Resource
	private DrivingLicenseBizService drivingLicenseBizService;
	
	@Resource
	private DrivingLicenseRecognitionService drivingLicenseRecognitionService;
	
	@Resource
	private CreditRecognitionService creditRecognitionService;
	
	@Resource
	private BlacklistService blacklistService;
	
	@Resource
	private SmsBizService smsBizService;
	
	@Resource
	private MessageTemplateService messageTemplateService;
	
	@Resource
	private RiskEmailService riskEmailService;
	
	@Resource
	private FicoCreditInvestigationService ficoCreditInvestigationService;
	
	@Resource
	private UserBizService userBizService;
	
	/**
	 * 人脸识别
	 * @param createVo
	 * @return
	 */
	@Override
	public ResponseResult<String> getFaceIdentity(IdentityCreateVo createVo) {
		
		Boolean flag = faceRecognitionService.getVerifyResult(createVo.getIdNumber(), DateUtil.getNDays(-verifyDays));
		if(flag) {
			return new ResponseResult<String>().success();
		}
		IdentityCreateDto createDto=new IdentityCreateDto();
		BeanUtils.copyProperties(createVo, createDto);
		ResponseResult<String> response = identityBizService.getFaceIdentity(createDto);
		Integer verifyResult=VerifyResultEnum.PASS.getValue();
		if(!response.getCode().equals(0)) {
			verifyResult=VerifyResultEnum.NO_PASS.getValue();
		}
		//保存人脸识别验证信息
		saveFaceRecognition(createVo,verifyResult);
		return response;
	}
	
	/**
	 * 征信
	 * @param terminalToken
	 * @return
	 */
	@Override
	public ResponseResult<String> getCredit(String terminalToken) {
		UserVo userVo = tokenUtil.getUserVo(terminalToken);
		Integer userId = userVo.getUserId();
		Assert.notNull(userId,"用户id不能为空");
		String idNumber = userVo.getIdNumber();
		Assert.hasLength(idNumber, "用户省份证号不能为空");
		String realName = userVo.getRealName();
		Assert.hasLength(realName, "用户姓名不能为空");
		String phone = userVo.getPhone();
		Assert.hasLength(phone, "用户手机号不能为空");
		
		BlacklistDto blacklist = blacklistService.getBlacklist(phone);
		if(null != blacklist) {
			throw new BizException(1,"抱歉，您未通过征信验证");
		}
		
		Boolean flagCredit = creditRecognitionService.getVerifyResult(userVo.getUserId(), DateUtil.getNDays(-verifyDays));
		if(flagCredit) {
			return new ResponseResult<String>().success();
		}
		MobileCreateDto createDto = new MobileCreateDto();
		createDto.setRealName(realName);
		createDto.setIdNumber(idNumber);
		createDto.setPhone(phone);
		return getCredit(createDto,userId);
	}
	
	 /**
     * 获取征信信息
     * @param createDto
     * @param userId
     * @return
     */
    private ResponseResult<String> getCredit(MobileCreateDto createDto,Integer userId){
    	ResponseResult<String> respone = null;
    	CreditDto creditDto = null;
		Integer verifySource = null; 
    	if(ficoIsTrue) {
			respone = ficoCreditInvestigationService.creditInvestigation(createDto);
			verifySource = CreditVerifySourceEnum.FICO.getValue();
		}else {
			ResponseResult<CreditDto> creditResponse = mobileBizService.getCredit(createDto);
			creditDto = creditResponse.getData();
			verifySource = CreditVerifySourceEnum.PY.getValue();
			if(creditResponse.getCode().equals(0)) {
				respone=new ResponseResult<String>().success();
			}else {
				respone=new ResponseResult<String>().error(creditResponse.getCode(), creditResponse.getMessage());
			}
		}
    	Integer verifyResult=VerifyResultEnum.PASS.getValue();
    	if(!respone.getCode().equals(0)) {
    		verifyResult=VerifyResultEnum.NO_PASS.getValue();
    		saveCreditRecognition(createDto.getPhone(),verifyResult,userId,creditDto,verifySource);
        	return respone;
    	}
    	saveCreditRecognition(createDto.getPhone(),verifyResult,userId,creditDto,verifySource);
    	return respone;
    }
    
    /**
	 * 保存征信验证结果
	 * 
	 * @param phone
	 * @param verifyResult
	 * @param userId
	 * @param creditDto
	 * @param verifySource
	 */
	private void saveCreditRecognition(String phone, Integer verifyResult, Integer userId,CreditDto creditDto,Integer verifySource) {
		CreditRecognitionCreateDto createDto = new CreditRecognitionCreateDto();
		createDto.setUserId(userId);
		createDto.setPhone(phone);
		createDto.setVerifyResult(verifyResult);
		createDto.setVerifyTime(LocalDateTime.now());
		if(null != creditDto) {
			createDto.setRiskScore(creditDto.getRiskScore());
			createDto.setScore(creditDto.getScore());
		}
		createDto.setVerifySource(verifySource);
		creditRecognitionService.create(createDto);
	}
	
	/**
	 * 保存人脸识别验证信息
	 * @param createVo
	 * @param verifyResult
	 */
	private void saveFaceRecognition(IdentityCreateVo createVo,Integer verifyResult) {
		FaceRecognitionCreateDto createDto =new FaceRecognitionCreateDto();
		createDto.setIdNumber(createVo.getIdNumber());
		createDto.setIdCardHeadImg(createVo.getPhoto());
		createDto.setPhotoHeadImg(createVo.getCompressPhoto());
		createDto.setVerifyResult(verifyResult);
		createDto.setVerifyTime(DateUtil.convertDateToLDT(new Date()));
		faceRecognitionService.create(createDto);
	}
	
	/**
	 * 驾驶证
	 * @param createVo
	 * @return
	 */
	@Override
	public ResponseResult<String> getDrivingLicense() {
		UserVo userVo = RequestAttrUtil.getCurrentUser();
		Integer userId = userVo.getUserId();
		Assert.notNull(userId,"用户id不能为空");
		String idNumber = userVo.getIdNumber();
		Assert.hasLength(idNumber, "用户省份证号不能为空");
		String realName = userVo.getRealName();
		Assert.hasLength(realName, "用户姓名不能为空");
		DrivingLicenseDto drivingLicense = drivingLicenseService.getDrivingLicense(userId);
		
		DrivingLicenseCreateDto createDto=new DrivingLicenseCreateDto();
		createDto.setIdNumber(idNumber);
		createDto.setRealName(realName);
		if(null == drivingLicense) {
			return getDrivingLicense(createDto,userVo);
		}
		//验证本地数据30天内
		long beforeTime= DateUtil.getNDays(-verifyDays).toInstant(ZoneOffset.of("+8")).toEpochMilli();
		long verifyTime = drivingLicense.getVerifyTime().toInstant(ZoneOffset.of("+8")).toEpochMilli();
		if(verifyTime < beforeTime) {
			return getDrivingLicense(createDto,userVo);
		}
		
		if(DrivingLicenseDataSourceEnum.LABOUR_JUDGE.getValue() == drivingLicense.getDataSource()) {
			if(DrivingLicenseStatusEnum.WAIT_PASS.getValue() == drivingLicense.getStatus()) {
				return new ResponseResult<String>().error(452,
						"您的驾驶证正在进行人工审核，工作日审核2小时以内，审核结果会第一时间短信通知您！客服热线：");
			}
			if(DrivingLicenseStatusEnum.VERIFY_PASS.getValue() != drivingLicense.getStatus()) {
				return getDrivingLicense(createDto,userVo);
			}
		}else {
			if(DrivingLicenseStatusEnum.VERIFY_PASS.getValue() != drivingLicense.getStatus()) {
				return new ResponseResult<String>().error(450,"抱歉，您的驾驶证未通过验证");
			}
		}
		
		return new ResponseResult<String>().success();
	}
	
	/**
	 * 获取驾驶证信息
	 * @param createDto
	 * @param userVo
	 * @return
	 */
	private ResponseResult<String> getDrivingLicense(DrivingLicenseCreateDto createDto,UserVo userVo){
		ResponseResult<DriverLicenseDto> responseResult = drivingLicenseBizService.getDrivingLicense(createDto);
		if(responseResult.getCode().equals(0)) {
			//保存驾驶证信息
			modifyDrivingLicense(responseResult.getData(),userVo,true);
			return new ResponseResult<String>().success();
		}else if(responseResult.getCode().equals(110)) {
			return new ResponseResult<String>().error(451,responseResult.getMessage());
		}else {
			//保存驾驶证信息
			modifyDrivingLicense(responseResult.getData(),userVo,false);
			return new ResponseResult<String>().error(450,responseResult.getMessage());
		}
	}
	
	
	/**
	 * 保存驾驶证验证信息
	 * @param createVo
	 * @param verifyResult
	 */
	private void saveDrivingLicenseRecognition(Integer userId,Integer verifyResult) {
		DrivingLicenseRecognitionCreateDto createDto =new DrivingLicenseRecognitionCreateDto();
		createDto.setUserId(userId);
		createDto.setVerifyResult(verifyResult);
		createDto.setVerifyTime(DateUtil.convertDateToLDT(new Date()));
		drivingLicenseRecognitionService.create(createDto);
	}
	
	/**
	 * 修改驾照证信息
	 * @param dto
	 * @param userVo
	 * @param flag true：通过  false ：失败
	 * @return
	 */
	private Boolean modifyDrivingLicense(DriverLicenseDto dto,UserVo userVo,Boolean flag) {
		DrivingLicenseModifyDto modifyDto = new DrivingLicenseModifyDto();
		modifyDto.setId(userVo.getUserId());
		modifyDto.setName(userVo.getRealName());
		modifyDto.setLicenseCode(userVo.getIdNumber());
		modifyDto.setModel(dto.getCarClass());
		modifyDto.setAddress(dto.getIssuePlace());
		modifyDto.setArchivesCode(dto.getFileNo());
		//（1：orc识别（人工），2：第三方接口）
		modifyDto.setDataSource(2);
		modifyDto.setVerifyTime(LocalDateTime.now());
		modifyDto.setStatus(dto.getStatus());
		int verifyResult = VerifyResultEnum.NO_PASS.getValue();
		if(flag) {
			 verifyResult = VerifyResultEnum.PASS.getValue();
		}
		saveDrivingLicenseRecognition(userVo.getUserId(),verifyResult);
		return drivingLicenseService.modify(modifyDto);
	}
	
	/**
	 * 驾驶证ocr
	 * @param createVo
	 * @return
	 */
	@Override
	public ResponseResult<DrivingLicenseOcrVo> getOcrDrivingLicense(DrivingLicenseOcrCreateVo createVo) {
		UserVo userVo = RequestAttrUtil.getCurrentUser();
		String idNumber = userVo.getIdNumber();
		String realName = userVo.getRealName();
		ResponseResult<DriverLicenseOcrDto> response = drivingLicenseBizService.getOcrDrivingLicense(createVo.getFrontalPhotoUrl());
		DriverLicenseOcrDto ocrDto = response.getData();
		DrivingLicenseOcrVo ocrVo = getOcrVo(ocrDto);
		if(!realName.equals(ocrDto.getName())) {
			modifyDrivingLicense(ocrDto,userVo,false,createVo);
			return new ResponseResult<DrivingLicenseOcrVo>().error(450,"驾驶证号与身份证号不一致",ocrVo);
			
		}
		
        if(!idNumber.equals(ocrDto.getLicenseCode())) {
        	modifyDrivingLicense(ocrDto,userVo,false,createVo);
        	return new ResponseResult<DrivingLicenseOcrVo>().error(450,"驾驶证号与身份证号不一致",ocrVo);
		}
        
		if(!response.getCode().equals(0)) {
			modifyDrivingLicense(ocrDto,userVo,false,createVo);
        	return new ResponseResult<DrivingLicenseOcrVo>().error(450,response.getMessage(),ocrVo);
		}
		
		modifyDrivingLicense(ocrDto,userVo,true,createVo);
    	return new ResponseResult<DrivingLicenseOcrVo>().success(ocrVo);
	}
	/**
	 * 获取ocrVo
	 * @param dto
	 * @return
	 */
	private DrivingLicenseOcrVo getOcrVo(DriverLicenseOcrDto dto) {
		DrivingLicenseOcrVo ocrVo=new DrivingLicenseOcrVo();
		ocrVo.setName(dto.getName());
		ocrVo.setLicenseCode(dto.getLicenseCode());
		ocrVo.setModel(dto.getModel());
		return ocrVo;
	}
	
	/**
	 * 修改驾照证信息
	 * @param dto
	 * @param userVo
	 * @param flag true：通过  false ：失败
	 * @return
	 */
	private Boolean modifyDrivingLicense(DriverLicenseOcrDto dto,UserVo userVo,Boolean flag,DrivingLicenseOcrCreateVo createVo) {
		DrivingLicenseModifyDto modifyDto = new DrivingLicenseModifyDto();
		modifyDto.setId(userVo.getUserId());
		modifyDto.setName(userVo.getRealName());
		modifyDto.setFrontalPhotoUrl(createVo.getFrontalPhotoUrl());
		modifyDto.setNegativePhotoUrl(createVo.getNegativePhotoUrl());
		modifyDto.setName(dto.getName());
		modifyDto.setSex(dto.getSex());
		modifyDto.setBirthDate(dto.getBirthDate());
		modifyDto.setLicenseCode(dto.getLicenseCode());
		modifyDto.setModel(dto.getModel());
		modifyDto.setAddress(dto.getAddress());
		modifyDto.setNationality(dto.getNationality());
		//（1：orc识别（人工），2：第三方接口）
		modifyDto.setDataSource(1);
		modifyDto.setVerifyTime(LocalDateTime.now());
		modifyDto.setStatus(DrivingLicenseStatusEnum.VERIFY_FAILURE.getValue());
		if(flag) {
			 int verifyResult = VerifyResultEnum.PASS.getValue();
			 saveDrivingLicenseRecognition(userVo.getUserId(),verifyResult);
			 modifyDto.setStatus(DrivingLicenseStatusEnum.VERIFY_PASS.getValue());
		}
		return drivingLicenseService.modify(modifyDto);
	}
	
	/**
	 * 修改驾驶证信息（提交人工审核）
	 * @return
	 */
	@Override
	public Boolean modifyStatus() {
		UserVo userVo = RequestAttrUtil.getCurrentUser();
		DrivingLicenseModifyDto modifyDto =new DrivingLicenseModifyDto();
		modifyDto.setId(userVo.getUserId());
		modifyDto.setStatus(DrivingLicenseStatusEnum.WAIT_PASS.getValue());
		Boolean flag = drivingLicenseService.modifyStatus(modifyDto);
		if(flag) {
			//驾驶证提交人工审核发送短信
			getPhone(userVo);
			//查询模板信息
			Map<String, MessageTemplateDto> map = getByKeys();
			if(null != map) {
				//驾驶证人工审核提醒信息 钉钉发送
				sendDingTalk(userVo,map);
				//驾驶证人工审核提醒信息 发送邮件
				sendEmail(userVo,map);
			}
		}
		return flag;
	}
	
	/**
	 * 驾驶证提交人工审核发送短信
	 * @param userVo
	 * @param phone
	 */
	private void sendNote(UserVo userVo,String phone) {
		JSONObject json=new JSONObject();
	    json.put("name", userVo.getRealName());
	    json.put("phone", userVo.getPhone());
	    try {
	    	smsBizService.sendMessage(phone, SmsTemplateEnum.DRIVING_SUBMIT_AUDIT.getValue(), json.toJSONString(), null);
		} catch (Exception e) {
			logger.error("驾驶证提交人工审核发送短信失败",e);
		}
	}
	

	/**
	 * 驾驶证人工审核提醒信息 钉钉发送
	 * @param userVo
	 * @param map
	 */
	private void sendDingTalk(UserVo userVo,Map<String,MessageTemplateDto> map) {
		MessageTemplateDto dto = map.get(drivingLicenceAuditDing);
		if(null == dto) {
			return;
		}
		String body = dto.getBody();
		if(StringUtils.isNoneBlank(body)) {
			body= body.replace("${name}", userVo.getRealName()).replace("${phone}", userVo.getPhone());
			DingTalkUtil.execute(drivingLicenceAuditUrl, body);
		}
	}
	
	/**
	 * 查询模板信息
	 * @return
	 */
	private Map<String,MessageTemplateDto> getByKeys(){
		List<String> keys= new ArrayList<>();
	    keys.add(drivingLicenceAuditDing);
	    keys.add(drivingLicenceAuditEmail);
	    try {
	    	 Map<String,MessageTemplateDto> map = messageTemplateService.getByKey(keys);
	    	 return map;
		} catch (Exception e) {
			logger.error("查询消息模板异常",e);
			return null;
		}
	}
	
	/**
	 * 驾驶证人工审核提醒信息 发送邮件
	 * @param userVo
	 * @param map
	 */
	private void sendEmail(UserVo userVo,Map<String,MessageTemplateDto> map) {
		MessageTemplateDto dto = map.get(drivingLicenceAuditEmail);
		if(null == dto) {
			return;
		}
		try {
			String subject = dto.getSubject();
			String body = dto.getBody();
			if(StringUtils.isNoneBlank(subject) && StringUtils.isNoneBlank(body)) {
				subject= subject.replace("${name}", userVo.getRealName()).replace("${phone}", userVo.getPhone());
				body= body.replace("${name}", userVo.getRealName()).replace("${phone}", userVo.getPhone());
				List<String> emailTo = getEmail();
				EmailUtil.sendMail(emailAccount, emailPassword, subject,body,emailTo);
			}
		} catch (Exception e) {
			logger.error("发送邮件异常",e);
		}
	}
	
	/**
	 * 获取邮件人信息
	 * @return
	 */
	private List<String> getEmail(){
	    List<RiskEmailDto> riskList = riskEmailService.getByType(RiskEmailTypeEnum.DRIVINGLICENSE_AUDIT.getValue(),RiskEmailReceiveTypeEnum.EMAIL_RECIPIENT.getValue());
	    List<String> list=null;
	    if(null != riskList && !riskList.isEmpty()) {
	    	list=new ArrayList<>();
	    	for (RiskEmailDto dto : riskList) {
				list.add(dto.getEmail());
			}
	    }
	    return list;
	}
	
	/**
	 * 获取发送手机人信息
	 * @return
	 */
	private void getPhone(UserVo userVo){
	    List<RiskEmailDto> riskList = riskEmailService.getByType(RiskEmailTypeEnum.DRIVINGLICENSE_AUDIT_PHONE.getValue(),RiskEmailReceiveTypeEnum.PHONE_SMS.getValue());
	    if(null != riskList && !riskList.isEmpty()) {
	    	for (RiskEmailDto dto : riskList) {
	    		//发送短信
	    		sendNote(userVo,dto.getEmail());
			}
	    }
	   
	}
	
	/**
	 * 初始化驾驶证信息
	 * @return
	 */
	@Override
	public ResponseResult<String> getGztDrivingLicense() {
		
//		String userIds ="146,148,152,153,159,161,166,174,175,181,194,192,200,212,216,218,221,222,223,225,230,231,238,279,282,289,294,300,302,303,308,313,316,319,318,321,324,325,326,329,333,339,344,350,351,352,355,354,359,373,374,380,381,383,385,387,389,388,392,393,397,398,399,402,405,407,409,414,416,418,421,423,425,426,427,390,430,255,434,436,437,438,447,449,454,455,457,458,460,463,442,466,470,498,500,508,510,516,517,520,523,527,524,530,536,540,542,543,545,547,549,553,556,559,561,564,565,572,575,574,578,581,580,579,587,590,598,600,602,601,614,616,626,627,629,622,642,643,645,646,647,652,655,656,657,658,606,659,445,663,668,669,670,671,674,679,682,684,688,693,695,680,697,704,707,708,710,711,709,712,683,735,738,715,745,747,748,757,758,761,764,767,770,773,772,776,777,778,781,787,788,789,794,795,796,797,793,798,799,790,803,804,666,808,813,811,818,828,830,832,833,836,802,835,834,838,840,841,839,844,847,848,851,852,853,859,860,862,865,867,868,869,870,873,875,821,876,877,880,883,882,893,894,734,889,884,902,280,910,909,914,915,917,916,918,863,927,926,929,933,938,940,941,943,945,946,949,948,952,956,959,960,961,962,963,969,972,971,973,977,976,978,823,982,985,986,987,991,980,996,997,998,999,1000,1001,1002,1003,925,1005,1006,1007,1011,1004,1016,1017,1022,1026,1030,1032,1033,1034,1035,1037,1040,1043,1044,953,1047,1051,1053,1054,1046,1056,1059,1061,1065,1067,1069,1072,1073,1075,1077,1078,905,1081,1084,1082,1086,1089,1094,1096,3945,1099,1101,1111,1119,1122,1124,1133,1135,1141,1143,1144,1145,1147,1041,1150,1151,1085,1155,1157,1158,1163,1164,1166,1168,1169,1170,1172,1173,1175,1176,1177,1178,1182,1183,1190,1188,1194,1197,1198,1199,1200,1195,1208,1205,1210,1211,1217,1224,1222,1225,1227,1130,1235,1241,1242,1247,1248,1256,1258,1263,1062,1262,1265,1264,1270,1273,1277,1279,1272,1280,1284,1288,1289,1290,1293,1296,1287,1300,1302,1309,1312,1314,1315,1319,1320,1322,1323,1324,1327,1329,1332,1334,1335,1330,1337,1340,1341,1311,1348,1347,1349,1353,1354,1357,1356,1360,1363,1366,1369,1371,1373,1378,1377,1380,1381,1383,1385,1386,1389,1394,1398,1400,1401,1399,1402,1411,1407,1413,1420,1421,1422,1423,1424,1428,1429,1430,1435,1433,1442,1443,1444,1440,1445,1456,1457,1458,1460,1461,1447,1466,1474,1486,1488,1489,1494,1500,1501,1503,1507,1455,1513,1515,1520,1526,1528,1543,1547,1550,1554,1561,1365,1567,1568,1574,334,1582,1571,1120,1591,1592,1594,1542,1471,1596,1589,1597,1267,1564,1608,1609,1613,1616,1617,1618,1533,1619,1620,1622,1621,1624,1625,732,1630,1634,1635,1632,1638,1639,1631,1641,1642,1637,1645,1646,1652,1655,1656,1658,1661,1660,1664,1665,1364,1670,1671,1673,1674,1672,1668,1683,1686,1690,1692,1693,1697,1698,1702,1704,1708,1710,1711,1714,1722,1725,1730,1731,1734,1737,1738,1739,1648,1742,1747,1753,1754,1755,1760,1763,1766,1770,1778,1761,1518,1784,1786,1790,1793,1800,1787,1807,1798,1809,1811,1810,1816,1814,1821,1823,1826,1827,1830,1829,1832,1834,1837,1838,1828,1843,1836,1848,1851,1854,1856,1858,1863,1864,1867,1735,1878,1877,1649,1882,1888,1741,1890,1889,1894,1896,1897,1895,1900,1901,1903,1907,1911,1910,1913,1917,1918,1922,1923,1931,1934,1936,1938,1939,1368,1943,1944,1947,1956,1958,1644,1961,1962,1959,1973,1929,1976,1978,1977,1981,1982,1991,1992,1990,1994,1998,2000,2004,2005,2011,1960,2017,1576,2016,2021,2027,2034,2038,2045,2040,2042,2048,1236,2046,2057,2058,2060,2055,2059,2062,2068,2069,2072,2074,2081,2086,2077,2090,2091,2093,2097,2105,2104,2109,2111,2113,2087,2115,2119,2122,2126,2127,2133,2136,2139,2140,2141,2142,2145,2147,2155,2159,2162,2165,2125,2168,2171,2177,2179,2178,2180,1801,2183,2118,1577,1935,2192,2198,2102,2199,2201,2202,2208,2209,2211,2212,2213,2215,2216,2217,2210,2219,2184,2222,2228,2231,2229,2224,2236,2237,2241,2238,1281,2249,2250,2256,2259,2264,2265,2267,2276,2278,2282,2284,2279,2286,2287,2273,2274,2290,2298,2301,2303,2306,2304,2311,2317,2318,2319,2321,2323,2326,2328,2299,2330,2331,2329,2333,2335,2342,2343,2348,2349,2351,2354,2355,2361,2363,2366,2370,2372,2375,2374,2376,2378,2381,2384,2385,2386,2394,2398,2402,2396,2407,2408,2410,2411,2409,2419,2427,2428,2432,2437,2439,2443,2441,2447,2446,2449,2450,2452,2455,2456,2457,2460,2461,2464,2462,2465,2466,2468,2471,2473,2477,2478,2476,2484,2481,2487,2488,2489,2490,2491,2493,2492,2496,2498,2499,2502,2507,2503,2509,1779,2472,2516,2519,2522,2523,2526,2520,2528,2530,2534,2536,2537,2538,2540,2544,2390,2546,2550,2548,1604,2565,2545,2573,2572,2581,2563,2543,2588,2597,2599,2600,2603,2606,2604,2614,2620,2621,2622,2616,2623,2624,2625,2626,2628,2629,2630,2631,2632,2634,2635,2636,2638,2645,2646,2664,2667,2673,2429,2677,2680,2682,2687,2690,2698,4412,2692,4413,2703,4414,2706,2708,2710,2714,2612,2715,2719,2720,2721,2722,2723,2727,2728,2730,2737,2740,2743,2745,2746,2747,2752,2748,2754,2759,2761,2766,2764,2769,2767,2774,2776,2778,2779,2781,2782,2784,2786,2791,2792,2794,2800,2801,2802,2803,2423,2806,2583,2807,2809,2810,2811,2812,2815,2816,2818,2820,2822,2824,2828,2829,2838,2841,2842,2846,2850,2852,4415,2853,2856,2857,4416,2863,2859,2860,4417,2868,2869,2871,2873,2880,2875,2881,2885,2877,2886,1773,2892,2898,2900,2901,2902,2905,2907,2908,2911,2912,2910,2913,2914,2916,827,2917,2919,2920,2923,2931,2933,2936,2939,2942,2943,2945,768,2951,2949,2953,2954,1372,2958,2957,2963,2223,613,2964,2891,2966,2973,2974,2975,2977,2978,2980,2987,2989,2990,2991,2992,2725,2995,2998,3000,3003,3004,3007,3008,3009,3014,3012,3020,3022,3023,3030,3019,3038,3047,3048,3049,3050,3051,3052,3054,2862,3066,3068,3074,3087,3090,3091,3080,3092,3093,3105,3106,3112,3119,3123,3126,3129,3131,3135,3141,3142,3144,3147,3149,3156,3158,3167,3173,3174,3176,3179,3187,3191,3197,3200,3161,3212,3208,3214,3216,3217,3215,3069,3226,3227,3231,3244,3241,3230,3275,3278,3279,3282,3283,3286,3290,3298,3304,3315,3316,3319,3312,3324,3329,3333,3338,2506,3341,3342,3347,3352,3354,3357,3360,3358,3353,3368,3369,3371,3372,3373,2009,3382,3387,3388,3394,3395,3396,3397,3399,3404,3409,3410,3405,3413,3402,3422,3424,3425,3426,3431,3432,3430,3445,3451,3452";
		String userIds ="11,15,16";
		String[] split = userIds.split(",");
		List<String> listOne =  new ArrayList<>();
		List<String> listTwo =  new ArrayList<>();
		for (String userId : split) {
			UserBizDto userBizDto = userBizService.getUser(Integer.valueOf(userId));
			UserVo userVo = Convert.toUserVo(userBizDto);
			DrivingLicenseCreateDto createDto=new DrivingLicenseCreateDto();
			createDto.setIdNumber(userVo.getIdNumber());
			createDto.setRealName(userVo.getRealName());
			ResponseResult<DriverLicenseDto> responseResult = drivingLicenseBizService.getDrivingLicense(createDto);
			if(responseResult.getCode().equals(0)) {
				//保存驾驶证信息
				modifyDrivingLicense(responseResult.getData(),userVo,true);
				
			}else if(responseResult.getCode().equals(110)) {
				listOne.add(userId);
			}else {
				//保存驾驶证信息
				modifyDrivingLicense(responseResult.getData(),userVo,false);
				listTwo.add(userId);
			}
		}
		
		String fileNameOne = "无驾驶证信息.xlsx";
        ByteArrayInputStream isOne = toUnableExcel(listOne);
        EmailUtil.sendMail(emailAccount, emailPassword, "无驾驶证信息","无驾驶证信息","liyiguang@molichuxing.com",fileNameOne,isOne);
        
    	String fileNameTwo = "驾驶证未通过.xlsx";
        ByteArrayInputStream isTwo = toUnableNoPassExcel(listTwo);
        EmailUtil.sendMail(emailAccount, emailPassword, "驾驶证未通过","驾驶证未通过","liyiguang@molichuxing.com",fileNameTwo,isTwo);
        
		return new ResponseResult<String>().success();
	}
	
    /**
     * 无驾驶证信息
     * @param list
     */
    private ByteArrayInputStream toUnableExcel(List<String> list){
        ByteArrayOutputStream baos = null;
        ByteArrayInputStream is = null;
        try {
                List<String> titles =new  ArrayList<>();
                titles.add(0, "userId");
                List<List<String>> params=new ArrayList<>();
                for (String userId : list) {
                    List<String> contents=new ArrayList<>();
                    contents.add(0,userId);
                    params.add(contents);
                }
                XSSFWorkbook createXSSFWorkbook = PoiExcelUtils.createXSSFWorkbook(titles, params);
                baos = new ByteArrayOutputStream();
                createXSSFWorkbook.write(baos);
                baos.flush();
                is = new ByteArrayInputStream(baos.toByteArray());

        } catch (Exception e) {
            logger.error("驾驶证数据初始化发邮件异常:", e);
        }finally {
            if(null!= baos) {
                try {
                    baos.close();
                } catch (IOException e) {

                }
            }
        }
        return is;
    }
    
    /**
     * 驾驶证未通过
     * @param list
     */
    private ByteArrayInputStream toUnableNoPassExcel(List<String> list){
        ByteArrayOutputStream baos = null;
        ByteArrayInputStream is = null;
        try {
                List<String> titles =new  ArrayList<>();
                titles.add(0, "userId");
                List<List<String>> params=new ArrayList<>();
                for (String userId : list) {
                    List<String> contents=new ArrayList<>();
                    contents.add(0,userId);
                    params.add(contents);
                }
                XSSFWorkbook createXSSFWorkbook = PoiExcelUtils.createXSSFWorkbook(titles, params);
                baos = new ByteArrayOutputStream();
                createXSSFWorkbook.write(baos);
                baos.flush();
                is = new ByteArrayInputStream(baos.toByteArray());

        } catch (Exception e) {
            logger.error("驾驶证数据初始化发邮件异常:", e);
        }finally {
            if(null!= baos) {
                try {
                    baos.close();
                } catch (IOException e) {

                }
            }
        }
        return is;
    }
    
}
